<template>
  <div class="b-uploader">
    <el-checkbox
      v-if="check"
      v-model="isCheck"
      class="b-uploader--checkbox"
      :disabled="!imageUrl"
      @change="handleFileChange"
    />
    <div class="b-uploader--input" @click="handleUpload">
      <input ref="fileInputRef" type="file" class="file-input" @change="handleImageChange" />
      <el-icon v-if="!imageUrl" size="20">
        <Plus />
      </el-icon>
      <img v-else class="b-uploader--img" :src="imageUrl" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: String
  },
  check: {
    type: Boolean,
    default: false
  }
})

const isCheck = ref(false)
const imageUrl = ref<string>()

onMounted(() => {
  imageUrl.value = props.modelValue
})

const emit = defineEmits({
  change: (url: string) => url,
  'update:model-value': (url: string) => url
})

const fileInputRef = ref()
function handleUpload() {
  fileInputRef.value.click()
}

function handleImageChange(e) {
  imageUrl.value = window.URL.createObjectURL(e.target.files[0])
  if (!props.check || (props.check && isCheck.value)) {
    emit('update:model-value', imageUrl.value)
    emit('change', imageUrl.value)
  }
}

function handleFileChange(val) {
  console.log(val)
  if (val) {
    emit('update:model-value', imageUrl.value)
    emit('change', imageUrl.value)
  } else {
    emit('update:model-value', '')
    emit('change', '')
  }
}
</script>
<style lang="scss" scoped>
.b-uploader {
  display: flex;
  justify-content: space-between;
  &--checkbox {
    margin-right: 10px;
  }
  &--input {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    min-width: 24px;
    height: 24px;
    border-radius: 4px;
    border: 1px solid var(--el-border-color);
    overflow: hidden;
    cursor: pointer;
    font-size: 14px;
  }

  .file-input {
    position: absolute;
    width: 100%;
    height: 100%;
    visibility: hidden;
  }

  &--img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
